package com.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;

import com.controller.dkjdcontroller;


/**
 * IP工具类
 * 
 */
public class OpenKey {

	/**
	 * 获取登录用户的IP地址
	 * 
	 * @param request
	 * @return
	 */
	private static final Logger logger = Logger.getLogger(dkjdcontroller.class);
	public static String getOpenKey(Map map,HttpSession session) throws ClientProtocolException, IOException {
		SessionInfo sessionIn = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		Date date=new Date();
		String interfaceUrl = ReadConfig.readValue();
		map.put("LOGUserName",Constant.username);
		String json = JSONUtil.ToJsongString2(map);
		String result = HttpRequest.doPost(interfaceUrl, json);
		Map retMap2 = JSONUtil.toMap(result);
		if(retMap2!=null){
			if("116".equals(retMap2.get("RETURNCODE").toString())||"115".equals(retMap2.get("RETURNCODE"))){
				System.out.println(date);
				SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
				String Key="";
				String a="";
				String Timestamp=sdf.format(date);
				String jm=Constant.mima+Timestamp+Constant.miyao;
				a=new MD5().getMD5(jm).toString();
				Map remap = new HashMap();
				BODY body = new BODY();
				remap.put("AUTHORITY", "YBGJJ100");
				remap.put("LOGUserName", Constant.username);
				body.setPassWd(a);
				body.setTimestamp(Timestamp);
				remap.put("BODY", body);
				
				String json3 = JSONUtil.ToJsongString2(remap);
				// 请求
				String result1 = HttpRequest.doPost(interfaceUrl, json3);
				logger.info("接口返回内容:" + result1);
	
				Map retMap = JSONUtil.toMap(result1);
				Map mx = JSONUtil.toMap(JSONUtil.ToJsongString2(retMap.get("body")));
				List jx = (List) mx.get("RETDATA");
				Map m = (Map) jx.get(0);
				String OpenKey = m.get("OpenKey").toString();
				System.out.println(OpenKey);
				
				sessionIn.setKEY(OpenKey);
				session.setAttribute(ConfigUtil.getSessionInfoName(),sessionIn);
				/****已查完KEY*****/
				map.put("OpenKey", OpenKey);
				String json4 = JSONUtil.ToJsongString2(map);
				String result4 = HttpRequest.doPost(interfaceUrl, json4);
				return result4;
			}else{
				return result;
			}
		}else{
			return result;
		}
	}
}
